﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using Hartley.ApplicationLogic;
using Hartley.DTOs;
using Hartley.Util;

namespace WebApplication1
{
    public partial class viewSportsDataAsGrid : System.Web.UI.Page
    {
        protected int currentPageNumber = 1;
        private const int PAGE_SIZE =5;
        List<TeamDTO> allTeamData;
        string queryString;
        string decryptedQueryString;
        SportsAL sportsAL;
        SportsUtil sportsUtil;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                BindData();

            }
        }

        private void BindData()
        {

            sportsAL = new SportsAL();
            sportsUtil = new SportsUtil();
            allTeamData = new List<TeamDTO>();
            List<TeamDTO> teamDataOfOnePage = new List<TeamDTO>();

            queryString = Request.QueryString.ToString();
            decryptedQueryString = sportsUtil.decryptQueryStrings(queryString); 
            string afterRemovedPlusSign = "";
            string afterReplaceComma = "";
            string correctedQueryString = "";
            string selectedCategory = "";


            int selectdYr;
            bool convertableToInteger = Int32.TryParse(decryptedQueryString, out selectdYr);

            if (convertableToInteger)
            {
                allTeamData = sportsAL.GetTeamByGameTypeByYearByAgeGruop("", selectdYr, "").OrderBy(a => a.GameType).OrderBy(b => b.AgeDivision).ToList();
                selectedCategory = "Year";
            }
            else
            {
                allTeamData = sportsAL.GetAllTeams();
            }

            if (decryptedQueryString.Contains('+'))
            {
                afterRemovedPlusSign = decryptedQueryString.Replace('+', ' ');
            }
            else
            {
                afterRemovedPlusSign = decryptedQueryString;
            }

            if (afterRemovedPlusSign.Contains("%2c"))
            {
                afterReplaceComma = afterRemovedPlusSign.Replace("%2c", ",");
            }
            else
            {
                afterReplaceComma = afterRemovedPlusSign;
            }
            correctedQueryString = afterReplaceComma;



            var gameTypes = (from m in allTeamData where correctedQueryString.Contains(m.GameType) select m).ToList();

            var ageDivisions = (from n in allTeamData where correctedQueryString.Contains(n.AgeDivision) select n).ToList();



            if (gameTypes.Count != 0)
            {
                foreach (string gameType in gameTypes.Select(a => a.GameType))
                {
                    allTeamData = sportsAL.GetTeamByGameTypeByYearByAgeGruop(gameType, 0, "").ToList().OrderByDescending(a => a.Year).OrderBy(c => c.AgeDivision).ToList();
                }
                selectedCategory = "GameType";
            }

            if (ageDivisions.Count != 0)
            {
                foreach (string dvsn in ageDivisions.Select(a => a.AgeDivision))
                {
                    allTeamData = sportsAL.GetTeamByGameTypeByYearByAgeGruop("", 0, dvsn).ToList().OrderByDescending(a => a.Year).OrderBy(c => c.GameType).ToList();
                }
                selectedCategory = "AgeDivision";
            }
          



            // get the total rows 
            double totalRows = (int)allTeamData.Count;

            lblAllSportsPage.Text = "Displaying all of the College Sports Data - Page ";
            lblAllSportsOf.Text = "  of  ";

            lblAllSportsTotalPage.Text = CalculateTotalPages(totalRows).ToString();

            lblAllSportsCurrPage.Text = currentPageNumber.ToString();

            if (Convert.ToInt32(lblAllSportsTotalPage.Text) < 3)
            {
                if (Int32.Parse(lblAllSportsTotalPage.Text) <= 0)
                {
                    btnAllSportsFirst.Enabled = false;
                    btnAllSportsPrev.Enabled = false;
                    btnAllSportsNext.Enabled = false;
                    btnAllSportsLast.Enabled = false;


                }

                if (currentPageNumber == 1)
                {
                    btnAllSportsFirst.Enabled = false;
                    btnAllSportsPrev.Enabled = false;

                    if (Int32.Parse(lblAllSportsTotalPage.Text) <= 0)
                    {
                        btnAllSportsFirst.Enabled = false;
                        btnAllSportsPrev.Enabled = false;
                        btnAllSportsNext.Enabled = false;
                        btnAllSportsLast.Enabled = false;


                    }
                    if (Int32.Parse(lblAllSportsTotalPage.Text) == 1)
                    {
                        teamDataOfOnePage = allTeamData.GetRange(0, Convert.ToInt32(totalRows));

                        btnAllSportsNext.Enabled = false;
                        btnAllSportsLast.Enabled = false;

                    }
                    else if (Int32.Parse(lblAllSportsTotalPage.Text) == 2)
                    {
                        teamDataOfOnePage = allTeamData.GetRange(0, PAGE_SIZE);

                        btnAllSportsNext.Enabled = true;
                        btnAllSportsLast.Enabled = true;

                    }


                }

                else
                {


                    if (currentPageNumber == Int32.Parse(lblAllSportsTotalPage.Text))
                    {
                        teamDataOfOnePage = allTeamData.GetRange((currentPageNumber - 1) * PAGE_SIZE 
                            , (Convert.ToInt32(totalRows) - (currentPageNumber - 1) * PAGE_SIZE ));

                        btnAllSportsNext.Enabled = false;
                        btnAllSportsLast.Enabled = false;

                    }
                    else
                    {
                        teamDataOfOnePage = allTeamData.GetRange((currentPageNumber - 1) * PAGE_SIZE , PAGE_SIZE );

                        btnAllSportsNext.Enabled = true;
                        btnAllSportsLast.Enabled = true;


                    }
                }

             


            }
            else
            {
                if (currentPageNumber == 1)
                {
                    teamDataOfOnePage = allTeamData.GetRange(0, PAGE_SIZE);

                    btnAllSportsFirst.Enabled = false;
                    btnAllSportsPrev.Enabled = false;
                    btnAllSportsNext.Enabled = true;
                    btnAllSportsLast.Enabled = true;

                }



                else
                {
                    btnAllSportsPrev.Enabled = true;
                    btnAllSportsFirst.Enabled = true;

                    if (currentPageNumber == Int32.Parse(lblAllSportsTotalPage.Text))
                    {
                        teamDataOfOnePage = allTeamData.GetRange((currentPageNumber - 1) * PAGE_SIZE
                            , (Convert.ToInt32(totalRows) - (currentPageNumber - 1) * PAGE_SIZE));

                        btnAllSportsNext.Enabled = false;
                        btnAllSportsLast.Enabled = false;

                    }
                    else
                    {
                        teamDataOfOnePage = allTeamData.GetRange((currentPageNumber - 1) * PAGE_SIZE, PAGE_SIZE);

                        btnAllSportsNext.Enabled = true;
                        btnAllSportsLast.Enabled = true;

                       
                    }


                }
            }

            // gvAllMeeting.DataSource = allMeetingsOfOnePage;
            // gvAllMeeting.DataBind();

            CreateDynamicTable(teamDataOfOnePage, selectedCategory);


        }

        private int CalculateTotalPages(double totalRows)
        {
            int totalPages = (int)Math.Ceiling(totalRows / (PAGE_SIZE));

            return totalPages;
        }

        protected void ChangePage(object sender, CommandEventArgs e)
        {

            switch (e.CommandName)
            {

                case "First":
                    currentPageNumber = 1;
                    break;

                case "Previous":
                    currentPageNumber = Int32.Parse(lblAllSportsCurrPage.Text) - 1;
                    break;

                case "Next":
                    currentPageNumber = Int32.Parse(lblAllSportsCurrPage.Text) + 1;
                    break;
                case "Last":
                    currentPageNumber = Int32.Parse(lblAllSportsTotalPage.Text);
                    break;
            }


            BindData();
        }


        private void CreateDynamicTable(List<TeamDTO> teamDataOfOnePage, string selectedCategory)
        {
            PlaceHolder4.Controls.Clear();

            // Fetch the number of Rows and Columns for the table 
            // using the properties

            int tblRows = teamDataOfOnePage.Count;
            
            lblSportsGrid.Text = "Tabular view of Sports data";
            PlaceHolder44.Controls.Add(lblSportsGrid);

            // Create a Table and set its properties 
            Table tbl = new Table();
            tbl.Width = new Unit("100%");
            tbl.BorderStyle = BorderStyle.Solid;
            // Add the table to the placeholder control
            PlaceHolder4.Controls.Add(tbl);

            TableRow trHeader = new TableRow();
            trHeader.Width = new Unit("25%");

            HyperLink hlSportsCellHeaderYear = new HyperLink();
            hlSportsCellHeaderYear.Text = "Year";

            HyperLink hlSportsCellHeaderGameType = new HyperLink();
            hlSportsCellHeaderGameType.Text = "Game Type";

            HyperLink hlSportsCellHeaderDivision = new HyperLink();
            hlSportsCellHeaderDivision.Text = "Age Division";

            HyperLink hlSportsCellHeaderMore = new HyperLink();
            hlSportsCellHeaderMore.Text = "Detail";
            //hlCompetitionCellHeaderMore.BackColor = System.Drawing.Color.DarkSlateBlue;
            //hlCompetitionCellHeaderMore.ForeColor = System.Drawing.Color.White;

            List<HyperLink> allHeaderHyperlinks = new List<HyperLink>();

            switch (selectedCategory)
            {
                case "Year":

            allHeaderHyperlinks.Add(hlSportsCellHeaderYear);
            allHeaderHyperlinks.Add(hlSportsCellHeaderGameType);
            allHeaderHyperlinks.Add(hlSportsCellHeaderDivision);
            allHeaderHyperlinks.Add(hlSportsCellHeaderMore);
                    break;

                case "GameType":

            allHeaderHyperlinks.Add(hlSportsCellHeaderGameType);
            allHeaderHyperlinks.Add(hlSportsCellHeaderYear);
            allHeaderHyperlinks.Add(hlSportsCellHeaderDivision);
            allHeaderHyperlinks.Add(hlSportsCellHeaderMore);

                    break;

                case "AgeDivision":
                    
            allHeaderHyperlinks.Add(hlSportsCellHeaderDivision);
            allHeaderHyperlinks.Add(hlSportsCellHeaderYear);
            allHeaderHyperlinks.Add(hlSportsCellHeaderGameType);
            allHeaderHyperlinks.Add(hlSportsCellHeaderMore);

                    break;
            }
           

            foreach (HyperLink hyperlinkHeader in allHeaderHyperlinks)
            {
                TableCell tcHeader = new TableCell();
                tcHeader.BackColor = System.Drawing.Color.DarkSlateBlue;
                tcHeader.ForeColor = System.Drawing.Color.White;

                tcHeader.Controls.Add(hyperlinkHeader);
                trHeader.Cells.Add(tcHeader);



            }

            tbl.Rows.Add(trHeader);
            

            // Now iterate through the table and add your controls 
            for (int i = 0; i < tblRows; i++)
            {
                TableRow tr = new TableRow();
                tr.Width = new Unit("25%");

                HyperLink hlSportsCellYear = new HyperLink();
                hlSportsCellYear.Text = teamDataOfOnePage[i].Year.ToString();

                HyperLink hlSportsCellGameType = new HyperLink();
                hlSportsCellGameType.Text = teamDataOfOnePage[i].GameType.ToString();

                HyperLink hlSportsCellDivision = new HyperLink();
                hlSportsCellDivision.Text = teamDataOfOnePage[i].AgeDivision;

                HyperLink hlSportsCellMore = new HyperLink();
                hlSportsCellMore.Text = "View More";


                queryString = Request.QueryString.ToString();



                if (selectedCategory == "Year")
                {
                    int selectdYear;
                    bool convertableToInt = Int32.TryParse(queryString, out selectdYear);

                    //allCompetitions = adminAL.GetAllResultsOfAYear(selectdYear.ToString());
                    hlSportsCellMore.NavigateUrl = "viewTeamById.aspx?"  + teamDataOfOnePage[i].TeamId ;
                }

                if (selectedCategory == "GameType")
                {
                    //int selectdYear;
                    //bool convertableToInt = Int32.TryParse(queryString, out selectdYear);

                    //allCompetitions = adminAL.GetAllResultsOfAYear(selectdYear.ToString());
                    hlSportsCellMore.NavigateUrl = "viewTeamById.aspx?"+ teamDataOfOnePage[i].TeamId ;
                }

                if (selectedCategory == "AgeDivision")
                {
                    // int selectdYear;
                    //bool convertableToInt = Int32.TryParse(queryString, out selectdYear);

                    //allCompetitions = adminAL.GetAllResultsOfAYear(selectdYear.ToString());
                    hlSportsCellMore.NavigateUrl = "viewTeamById.aspx?"  + teamDataOfOnePage[i].TeamId ;
                }



                List<HyperLink> allHyperlinks = new List<HyperLink>();
                switch (selectedCategory)
                {
                    case "Year":

                allHyperlinks.Add(hlSportsCellYear);
                allHyperlinks.Add(hlSportsCellGameType);
                allHyperlinks.Add(hlSportsCellDivision);
                allHyperlinks.Add(hlSportsCellMore);

                        break;

                    case "GameType":

              allHyperlinks.Add(hlSportsCellGameType);
              allHyperlinks.Add(hlSportsCellYear);
              allHyperlinks.Add(hlSportsCellDivision);
              allHyperlinks.Add(hlSportsCellMore);

                        break;

                    case "AgeDivision":

              allHyperlinks.Add(hlSportsCellDivision);
              allHyperlinks.Add(hlSportsCellYear);
              allHyperlinks.Add(hlSportsCellGameType);
              allHyperlinks.Add(hlSportsCellMore);
                        break;
                }


                
                

                foreach (HyperLink hyperlink in allHyperlinks)
                {
                    TableCell tc = new TableCell();



                    if (i % 2 == 0)
                    {
                        tc.Style.Add("background-color", "White");
                        tc.ForeColor = System.Drawing.Color.Blue;
                    }
                    else
                    {
                        tc.Style.Add("background-color", "#003399");
                        tc.ForeColor = System.Drawing.Color.White;

                    }



                    // Add the control to the TableCell
                    tc.Controls.Add(hyperlink);


                    // Add the TableCell to the TableRow
                    tr.Cells.Add(tc);
                }

                // Add the TableRow to the Table

                tbl.Rows.Add(tr);
            }

            // This parameter helps determine in the LoadViewState event,
            // whether to recreate the dynamic controls or not

            ViewState["dynamictable"] = true;
        }


    }
}